#include "gifframe.h"

namespace WingGif {

GifImageDescriptor *GifFrame::descriptor() { return _descriptor; }

QVector<GifColor> GifFrame::localColorTable() { return _localColorTable; }

QList<GifExtension *> GifFrame::extensions() { return _extensions; }

GifImageData *GifFrame::imageData() { return _imageData; }

GifFrame::GifFrame(QObject *parent) : GifBlock(parent) {}

GifBlockKind GifFrame::kind() { return GifBlockKind::GraphicRendering; }

bool GifFrame::read(QIODevice *stream,
                    QList<GifExtension *> controlExtensions) {
  _descriptor = new GifImageDescriptor(stream, this);

  if (_descriptor->hasLocalColorTable())
    _localColorTable =
        readColorTable(stream, _descriptor->localColorTableSize());

  _imageData = new GifImageData(stream, this);
  _extensions = controlExtensions;
  return true;
}

QVector<GifColor> GifFrame::readColorTable(QIODevice *stream, int size) {
  auto length = 3 * size;
  auto bytes = stream->read(length);
  QVector<GifColor> colorTable(size);

  for (auto i = 0; i < size; i++) {
    auto r = bytes[3 * i];
    auto g = bytes[3 * i + 1];
    auto b = bytes[3 * i + 2];
    colorTable[i] = GifColor::fromRgb(r, g, b);
  }
  return colorTable;
}

} // namespace WingGif
